from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
from models import Thing, User
import random, string, base64, urllib

class NewHandler(webapp.RequestHandler):
  def get(self):
    # Get the user from the db
    user = UserUtil.getUser()
    
    # Get a list of a number of strings with given length
    length = 24
    number = 1
    strings = self.getStrings(length, number)
    
    ## Loop through and output the QR Code images from Google Charts API
    for x in range(0,number):
      self.response.out.write('<img src="http://chart.apis.google.com/chart?cht=qr&chs=250x250&chld=M&chl=http://mangtug.appspot.com/ndm/thing/' + strings[x] + '" alt="QR Code of a NDM Thing" />')
  
  # Get list of a number of random string of a given length
  def getStrings(self, length, number):
    # Create a list
    list = []
    
    # Loop the number of strings and append a random string to the list
    for x in xrange(number):
      list.append(self.getString(length))
    
    # Return the list to the caller
    return list
  
  # A method to get a random string of ASCII characters of a given length and make sure it doesn't already exist
  def getString(self, length):
    # Get a random string
    # TODO: Make this random string generator less horrible
    generatedString = "".join([random.choice(string.ascii_letters + string.digits + ".-") for i in xrange(length)])
    
    # Check the string doesn't exist
    thingQuery = Thing.gql('WHERE thingid = :1 LIMIT 1', generatedString)
    if (thingQuery.count() == 0):
      # Add the generated string to the db so we know not to generate it again
      thing = Thing()
      thing.thingid = generatedString
      thing.author = self.loggedInUser.user_id()
      thing.put()
      
      # Return the string
      return generatedString
    else:
      # Use recursion to get a different one
      return self.getString(length)

class UnusedHandler(webapp.RequestHandler):
  def get(self):
    # Get the user from the db
    user = UserUtil.getUser()
    
    thingQuery = Thing.gql('WHERE author = :1 AND assigned = False', user.uniqueid)
    if (thingQuery.count() > 0):
      self.response.out.write('<h1>' + str(thingQuery.count()) + ' unused codes</h1>')
      
      for result in thingQuery:
        self.response.out.write('<p>Code: ' + result.thingid + '<br />')
        self.response.out.write('<img src="http://chart.apis.google.com/chart?cht=qr&chs=250x250&chld=M&chl=http://mangtug.appspot.com/ndm/thing/' + result.thingid + '" alt="QR Code of a NDM Thing" /></p>')
    else:
      self.response.out.write('No unused codes')

class MainHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<a href="/ndm/generate/unused/">See unused codes</a><br />')
    self.response.out.write('<a href="/ndm/generate/new/">Generate New</a>')

def main():
  application = webapp.WSGIApplication([
    ('/ndm/generate/new/*', NewHandler),
    ('/ndm/generate/unused/*', UnusedHandler),
    ('/ndm/generate/*', MainHandler),
  ], debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
